﻿using System;
using System.Activities.Statements;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Web.Services;
using Newtonsoft.Json;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://127.0.0.1")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 

[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{

    public WebService()
    {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    public static DataBaseHelper dataBaseHelper = null;

    [WebMethod(Description = "获取sql的json数据")]
    public string GetJsonData(string sql)
    {
        DataTable dataTable = dataBaseHelper.GetDataTable(sql);
        ArrayList arrayList = new ArrayList();
        foreach (DataRow dataRow in dataTable.Rows)
        {
            Dictionary<string, object> dictionary = new Dictionary<string, object>(); //实例化一个参数集合
            foreach (DataColumn dataColumn in dataTable.Columns)
            {
                dictionary.Add(dataColumn.ColumnName, dataRow[dataColumn.ColumnName].ToString());
            }
            arrayList.Add(dictionary); //ArrayList集合中添加键值
        }
        return JsonConvert.SerializeObject(arrayList);
    }

    [WebMethod(Description = "初始化mysql的连接")]
    public string InitMySql()
    {
        try
        {
            dataBaseHelper = new MySqlHelper();
            dataBaseHelper.Connecting = ConfigurationManager.ConnectionStrings["mysql"].ConnectionString;
            //dataBaseHelper.Init("127.0.0.1", "50015", "root", "10000", "WebTest");
        }
        catch (Exception exception)
        {
            Console.WriteLine(exception.Message);
        }

        Console.WriteLine(dataBaseHelper.Connecting);
        return dataBaseHelper.Connecting;
    }

    [WebMethod(Description = "创建GeoJson文件供前端加载")]
    public string SetCellGeoJsonData()
    {
        string sql =
            "Select longitude as x,latitude as y,ArcPts as points,LAC_CI as id,BTS_NAME as name,BCCH as value from dtdb_ningbo.cellinfo";
        string fileName = "data\\" + "cell.geojson";
        try
        {

            string filepath = Server.MapPath("~") + "data\\";
            if (!Directory.Exists(filepath))
                Directory.CreateDirectory(filepath);

            string fullPath = Server.MapPath("~") + "data\\" + "cell.geojson";

            if (File.Exists(fullPath))
            {
                File.Delete(fullPath);
            }

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.AppendLine("{");
            stringBuilder.AppendLine("\"type\": \"FeatureCollection\",");
            stringBuilder.AppendLine(
                "\"crs\": { \"type\": \"name\", \"properties\": { \"name\": \"urn:ogc:def:crs:OGC:1.3:CRS84\" } },");
            stringBuilder.AppendLine("\"features\": [");

            //处理datatable数据
            string geoFirst = "{ \"type\": \"Feature\", \"properties\": {" ;
                //" \"name\": \"";
            string getName = "name";
            string geoMiddle = "}, \"geometry\": { \"type\": \"";
            string geotype = "Point";
            string geocoord = "\", \"coordinates\": [";
            string geoPoints = string.Empty;
            string getLast = " ] } }";

            bool haveFeature = false;

            DataTable dataTable = dataBaseHelper.GetDataTable(sql);
            if (dataTable != null && dataTable.Columns.Count > 1)
            {
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    DataRow dataRow = dataTable.Rows[i];

                    getName = "\"name\":\"" + Convert.ToString(dataRow["name"]) + "\"" + ",\"id\":\"" + Convert.ToString(dataRow["id"]) + "\"," + "\"value\":\"" + Convert.ToString(dataRow["value"]) + "\"";

                    string x = Convert.ToString(dataRow["x"]);
                    
                    string y = Convert.ToString(dataRow["y"]);

                    string xys = Convert.ToString(dataRow["points"]);

                    #region 处理point类型

                    //if (!string.IsNullOrEmpty(x) && !string.IsNullOrEmpty(y))
                    //{
                    //    geotype = "Point";
                    //    geoPoints = x + "," + y;
                    //    string pointLine = geoFirst + getName + geoMiddle + geotype + geocoord + geoPoints + getLast;

                    //    if (!haveFeature)
                    //    {
                    //        stringBuilder.AppendLine(pointLine);
                    //        haveFeature = true;
                    //    }
                    //    else
                    //        stringBuilder.AppendLine(","+pointLine);

                    //}

                    #endregion

                    #region 处理polygon类型



                    if (!string.IsNullOrEmpty(xys))
                    {
                        bool canAddpolygon = true;

                        geotype = "Polygon";

                        geoPoints = "[" + "[" + x + "," + y + "]";

                        foreach (string xy in xys.Split(';'))
                        {
                            string[] xy1 = xy.Split(',');
                            if (xy1.Length == 2)
                            {
                                string x1 = xy1[0];
                                string y1 = xy1[1];

                                if (string.IsNullOrEmpty(x1) || string.IsNullOrEmpty(y1) || x1 == "0" || y1 == "0")
                                {
                                    canAddpolygon = false;
                                    break;
                                }

                                geoPoints = geoPoints + "," + "[" + x1 + "," + y1 + "]";
                            }
                        }

                        if (canAddpolygon)
                        {
                            geoPoints = geoPoints + ",[" + x + "," + y + "]]";
                            string polygonLine = geoFirst + getName + geoMiddle + geotype + geocoord + geoPoints +
                                                 getLast;

                            if (!haveFeature)
                            {
                                stringBuilder.AppendLine(polygonLine);
                                haveFeature = true;
                            }
                            else
                                stringBuilder.AppendLine("," + polygonLine);

                        }
                    }

                    #endregion
                }
            }

            stringBuilder.AppendLine("]");
            stringBuilder.AppendLine("}");

            using (StreamWriter streamWriter = new StreamWriter(fullPath))
            {
                streamWriter.Write(stringBuilder);
                streamWriter.Flush();
                streamWriter.Close();
            }
        }
        catch (Exception exception)
        {
            fileName = exception.Message;
            Console.WriteLine(exception.Message);
        }

        return fileName.Replace('\\', '/');
    }
}
